<template>
  <xr-create :loading="loading" :title="title" @close="close" @save="saveClick">
    <create-sections>
      <wk-form
        ref="crmForm"
        :model="fieldForm"
        :rules="fieldRules"
        :field-from="fieldForm"
        :field-list="fieldList"
        label-position="top"
        @change="formChange"
      />
    </create-sections>
  </xr-create>
</template>

<script>
import { addSignature } from "@/api/admin/agreement";

import XrCreate from "@/components/XrCreate";
import CreateSections from "@/components/CreateSections";
import WkForm from "@/components/NewCom/WkForm";

// import crmTypeModel from "@/views/crm/model/crmTypeModel";
import CustomFieldsMixin from "@/mixins/CustomFields";
import { isEmpty } from "@/utils/types";
import { mapGetters } from "vuex";
export default {
  // 新建编辑
  name: "create",

  components: {
    XrCreate,
    CreateSections,
    WkForm
  },

  mixins: [CustomFieldsMixin],

  props: {
    phone: String,
    action: {
      type: Object,
      default: () => {
        return {
          type: "save",
          id: "",
          data: {}
        };
      }
    }
  },

  data() {
    return {
      loading: false,
      baseFields: [],
      fieldList: [],
      fieldList1: [],
      fieldList2: [],
      fieldForm: {},
      fieldRules: {},
      fieldRules1: {},
      fieldRules2: {},
      templateFieldList: [
        {
          fieldName: "sealName",
          formType: "text", //  mobile
          name: "签章名称",
          type: 1,
          inputTips: '例如：电子专用章、合同专用章等',
          maxLength: null,
          defaultValue: "",
          isUnique: 0,
          isNull: 1,
          options: null,
          fieldType: 1,
          setting: [],
          authLevel: 3,
          value: null,
          sysInformation: null,
          autoGeneNumber: null,
          typeField: null,
          restrictType: null,
          restrictData: null,
          levelData: null,
          sorting: 1
        },
        {
          fieldName: "enterpriseName",
          formType: "text", //  mobile
          name: "企业名称",
          type: 1,
          inputTips: null,
          maxLength: null,
          defaultValue: "",
          isUnique: 0,
          isNull: 1,
          options: null,
          fieldType: 1,
          setting: [],
          authLevel: 3,
          value: null,
          sysInformation: null,
          autoGeneNumber: null,
          typeField: null,
          restrictType: null,
          restrictData: null,
          levelData: null,
          sorting: 1
        },
        {
          fieldName: "businessLicenseNum",
          formType: "text", //  mobile
          name: "组织机构代码号",
          type: 1,
          inputTips: null,
          maxLength: null,
          defaultValue: "",
          isUnique: 0,
          isNull: 1,
          options: null,
          fieldType: 1,
          setting: [],
          authLevel: 3,
          value: null,
          sysInformation: null,
          autoGeneNumber: null,
          typeField: null,
          restrictType: null,
          restrictData: null,
          levelData: null,
          sorting: 1
        },
        {
          fieldName: "corporationName",
          formType: "text", //  mobile
          name: "法人姓名",
          type: 1,
          inputTips: null,
          maxLength: null,
          defaultValue: "",
          isUnique: 0,
          isNull: 1,
          options: null,
          fieldType: 1,
          setting: [],
          authLevel: 3,
          value: null,
          sysInformation: null,
          autoGeneNumber: null,
          typeField: null,
          restrictType: null,
          restrictData: null,
          levelData: null,
          sorting: 1
        },
        {
          fieldName: "corporationCard",
          formType: "Card", //  mobile
          name: "法人身份证号",
          type: 1,
          inputTips: null,
          maxLength: 18,
          defaultValue: "",
          isUnique: 0,
          isNull: 1,
          options: null,
          fieldType: 1,
          setting: [],
          authLevel: 3,
          value: null,
          sysInformation: null,
          autoGeneNumber: null,
          typeField: null,
          restrictType: null,
          restrictData: null,
          levelData: null,
          sorting: 1
        },
        {
          fieldName: "corporationPhone",
          formType: "mobile",
          name: "法人手机号",
          type: 7,
          inputTips: null,
          maxLength: 11,
          defaultValue: "",
          isUnique: 0,
          isNull: 1,
          options: null,
          fieldType: 1,
          setting: [],
          authLevel: 3,
          value: null,
          sysInformation: null,
          autoGeneNumber: null,
          typeField: null,
          restrictType: null,
          restrictData: null,
          levelData: null,
          sorting: 1
        },
        {
          fieldName: "contactsName",
          formType: "text", //  mobile
          name: "联系人姓名",
          type: 1,
          inputTips: null,
          maxLength: null,
          defaultValue: "",
          isUnique: 0,
          isNull: 1,
          options: null,
          fieldType: 1,
          setting: [],
          authLevel: 3,
          value: null,
          sysInformation: null,
          autoGeneNumber: null,
          typeField: null,
          restrictType: null,
          restrictData: null,
          levelData: null,
          sorting: 1
        },
        {
          fieldName: "contactsCard",
          formType: "Card", //  mobile
          name: "联系人身份证号",
          type: 1,
          inputTips: null,
          maxLength: 18,
          defaultValue: "",
          isUnique: 0,
          isNull: 1,
          options: null,
          fieldType: 1,
          setting: [],
          authLevel: 3,
          value: null,
          sysInformation: null,
          autoGeneNumber: null,
          typeField: null,
          restrictType: null,
          restrictData: null,
          levelData: null,
          sorting: 1
        },
        {
          fieldName: "contactsPhone",
          formType: "mobile",
          name: "联系人手机号",
          type: 7,
          inputTips: null,
          maxLength: 11,
          defaultValue: "",
          isUnique: 0,
          isNull: 1,
          options: null,
          fieldType: 1,
          setting: [],
          authLevel: 3,
          value: null,
          sysInformation: null,
          autoGeneNumber: null,
          typeField: null,
          restrictType: null,
          restrictData: null,
          levelData: null,
          sorting: 1
        }
      ]
    };
  },

  computed: {
    ...mapGetters(["userInfo"]),
    title() {
      return this.action.type === "update" ? "编辑签章" : "添加签章主体";
    }
  },

  watch: {},

  created() {
    this.getField();
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * 获取数据
     */
    getField() {
      this.loading = true;
      const params = {
        // label: crmTypeModel.leads
      };

      if (this.action.type == "update") {
        params.id = this.action.id;
      }

      const list = this.templateFieldList || [];
      if (!isEmpty(this.phone)) {
        list.forEach(item => {
          if (item.formType === "mobile") {
            item.defaultValue = this.phone;
          }
        });
      }

      const fieldList = [];
      const fieldList1 = [];
      const fieldList2 = [];
      const fieldRules = {};
      const fieldRules1 = {};
      const fieldRules2 = {};
      const fieldForm = {};
      list.forEach(item => {
        const temp = {};
        temp.field = item.fieldName;
        temp.formType = item.formType;
        temp.fieldId = item.fieldId;
        temp.inputTips = item.inputTips;
        temp.name = item.name;
        temp.setting = item.setting;
        temp.levelData = item.levelData;
        temp.restrictData = item.restrictData;
        temp.displayShow = true;
        temp.maxlength = item.maxLength;
        if (item.formType === "select") {
          if (item.authLevel == 1) {
            temp.displayShow = true;
            temp.isNull = 0;
          } else {
            temp.displayShow = true;
          }
        }

        // if (item.fieldName === "telephone") {
        //   temp.maxlength = item.maxLength;
        // } else if (item.fieldName === "trainingPeriods") {
        //   temp.maxlength = item.maxLength;
        // }

        if (temp.fieldId == 1102117) {
          //销售类型回显
          let arr = [];
          for (let i = 0; i < item.setting.length; i++) {
            const obj = {
              label: item.setting[i],
              value: i + 1
            };
            arr.push(obj);
          }
          temp.setting = arr;
        }

        if (temp.formType == "single_user") {
          if (temp.field == "teacherId") {
            temp.isTeacher = true;
          } else {
            temp.isTeacher = false;
          }
        }

        const canEdit = this.getItemIsCanEdit(item, this.action.type);
        // 是否能编辑权限
        if (canEdit) {
          if (item.fieldName == "trainingPeriods") {
            fieldRules1[temp.field] = this.getRules(item);
          } else if (
            item.fieldName == "ownerUserId" ||
            item.fieldId == 1101914
          ) {
            fieldRules2[temp.field] = this.getRules(item);
          } else {
            fieldRules[temp.field] = this.getRules(item);
          }
        }

        // 是否可编辑
        temp.disabled = !canEdit;

        // 特殊字段允许多选
        this.getItemRadio(item, temp);
        fieldForm[temp.field] = this.getItemValue(
          item,
          this.action.data,
          this.action.type
        );
        if (this.action.type != "update") {
          if (item.fieldName == "leadsUserId") {
            fieldForm["leadsUserId"] = this.userInfo.userId;
          }
        }

        // 获取默认值
        if (item.fieldName == "trainingPeriods") {
          fieldList1.push(temp);
        } else if (item.fieldName == "ownerUserId" || item.fieldId == 1101914) {
          fieldList2.push(temp);
        } else {
          if (item.formType === "select") {
            if (item.authLevel == 1) {
              temp.displayShow = true;
              temp.isNull = 0;
            } else {
              fieldList.push(temp);
            }
          } else {
            fieldList.push(temp);
          }
        }
      });
      this.baseFields = list;
      this.fieldList = fieldList;
      this.fieldList1 = fieldList1;
      this.fieldList2 = fieldList2;
      this.fieldForm = fieldForm;
      // console.log(this.fieldForm,2222,fieldRules,fieldRules1,fieldRules2)
      this.fieldRules = fieldRules;
      this.fieldRules1 = fieldRules1;
      this.fieldRules2 = fieldRules2;
      this.loading = false;
    },

    /**
     * 保存
     */
    saveClick() {
      this.loading = true;
      const crmForm = this.$refs.crmForm.instance;
      let submitData = () => {
        const params = this.getSubmiteParams(this.baseFields, this.fieldForm);
        this.submiteParams(params);
      };
      crmForm.validate(valid => {
        if (valid) {
          if (this.fieldList1 && this.fieldList1.length > 0) {
            const crmForm1 = this.$refs.crmForm1.instance;
            crmForm1.validate(valid1 => {
              if (valid1) {
                submitData();
              } else {
                this.loading = false;
                // 提示第一个error
                this.getFormErrorMessage(crmForm);
                return false;
              }
            });
          } else {
            submitData();
          }
        } else {
          this.loading = false;
          // 提示第一个error
          this.getFormErrorMessage(crmForm);
          return false;
        }
      });
    },

    /**
     * 提交上传
     */
    submiteParams(params) {
      if (this.action.type == "update") {
        // params.entity.leadsId = this.action.id;
        // params.entity.batchId = this.action.batchId;
      }

      // 相关添加时候的多余提交信息
      if (
        this.action.relativeData &&
        Object.keys(this.action.relativeData).length
      ) {
        params = { ...params, ...this.action.relativeData };
      }
      // console.log(params);
      addSignature(params.entity)
        .then(res => {
          this.loading = false;
          this.$message.success(
            this.action.type == "update" ? "编辑成功" : "添加成功"
          );

          this.close();

          // 保存成功
          this.$emit("save-success", {
            type: "signature"
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 验证唯一
     */
    UniquePromise({ field, value }) {
      return this.getUniquePromise(field, value, this.action);
    },

    /**
     * change
     */
    formChange(item, index, value, valueList) {
      if (item.fieldId == 1101908) {
        //是否加微信
        this.fieldList[6].disabled = !(value == "是");
        this.fieldList[7].disabled = !(value == "是");
      }
    },

    /**
     * 地址change
     */
    otherChange(data, field) {
      this.$set(this.fieldForm, field.field, data.value);
      this.$refs.crmForm.instance.validateField(field.field);
    },

    /**
     * 关闭
     */
    close() {
      this.$emit("close");
    }
  }
};
</script>

<style lang="scss" scoped></style>
